using MediatR;
using Microsoft.AspNetCore.Mvc;
using Medical.ErrorCode;
using BaseData.ErrorCode;
using Medical.ReadApi.Appcontext.Command;
using Medical.ReadApi.Dto;

namespace Medical.ReadApi.Controllers
{
	/// <summary>
	/// 用户管理控制器（读操作）
	/// </summary>
	[ApiController]
	[Route("api/[controller]/[action]")]
	public class UserController : ControllerBase
	{
		private readonly IMediator _mediator;
		
		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="mediator">MediatR中介者</param>
		public UserController(IMediator mediator)
		{
			_mediator = mediator;
		}

		/// <summary>
		/// 用户登录
		/// </summary>
		/// <param name="query">登录查询，包含用户名和密码</param>
		/// <returns>登录响应，包含用户信息、Token、角色和权限</returns>
		/// <remarks>
		/// 示例请求:
		/// POST /api/User/Login
		/// {
		///   "userName": "admin",
		///   "password": "123456"
		/// }
		/// 
		/// 成功响应示例:
		/// {
		///   "code": 500,
		///   "message": "登录成功",
		///   "data": {
		///     "userId": 1,
		///     "userName": "admin",
		///     "fullName": "管理员",
		///     "token": "base64token...",
		///     "expiresAt": "2024-01-01T12:00:00",
		///     "roles": [...],
		///     "permissions": [...]
		///   }
		/// }
		/// </remarks>
		/// <response code="200">登录成功，返回用户信息和Token</response>
		/// <response code="400">请求参数错误</response>
		/// <response code="401">用户名或密码错误</response>
		/// <response code="500">服务器内部错误</response>
		[HttpPost]
		[ProducesResponseType(typeof(ApiResult<LoginResponseDto>), 200)]
		[ProducesResponseType(400)]
		[ProducesResponseType(401)]
		[ProducesResponseType(500)]
		public async Task<ApiResult<LoginResponseDto>> Login([FromBody] LoginUserQuery query)
		{
			try
			{
				var loginIp = HttpContext.Connection.RemoteIpAddress?.ToString();
				query.LoginIp = loginIp;
				var data = await _mediator.Send(query);
				return new ApiResult<LoginResponseDto> { Code = ApiEnum.登录成功, Message = "登录成功", data = data };
			}
			catch (Exception ex)
			{
				return new ApiResult<LoginResponseDto> { Code = ApiEnum.登录失败, Message = ex.Message, data = null };
			}
		}

		/// <summary>
		/// 获取用户列表（支持分页和筛选）
		/// </summary>
		/// <param name="userNameKeyword">用户名关键词（模糊搜索）</param>
		/// <param name="fullNameKeyword">真实姓名关键词（模糊搜索）</param>
		/// <param name="email">邮箱（精确匹配）</param>
		/// <param name="isActive">是否激活状态筛选</param>
		/// <param name="page">页码（从1开始，默认值：1）</param>
		/// <param name="size">每页数量（默认值：10）</param>
		/// <returns>分页的用户列表</returns>
		/// <remarks>
		/// 示例请求:
		/// GET /api/User/GetUsers?userNameKeyword=admin&amp;isActive=true&amp;page=1&amp;size=10
		/// 
		/// 所有查询参数都是可选的，可以任意组合使用。
		/// </remarks>
		/// <response code="200">查询成功，返回分页的用户列表</response>
		/// <response code="400">请求参数错误</response>
		/// <response code="500">服务器内部错误</response>
		[HttpGet]
		[ProducesResponseType(typeof(ApiResult<ApiPaging<UserDto>>), 200)]
		[ProducesResponseType(400)]
		[ProducesResponseType(500)]
		public async Task<ApiResult<ApiPaging<UserDto>>> GetUsers(
			[FromQuery] string? userNameKeyword = null,
			[FromQuery] string? fullNameKeyword = null,
			[FromQuery] string? email = null,
			[FromQuery] bool? isActive = null,
			[FromQuery] int page = 1,
			[FromQuery] int size = 10)
		{
			try
			{
				var data = await _mediator.Send(new GetUsersListQuery
				{
					UserNameKeyword = userNameKeyword,
					FullNameKeyword = fullNameKeyword,
					Email = email,
					IsActive = isActive,
					Page = page,
					Size = size
				});
				return new ApiResult<ApiPaging<UserDto>> { Code = ApiEnum.查询成功, Message = "查询成功", data = data };
			}
			catch (Exception ex)
			{
				return new ApiResult<ApiPaging<UserDto>> { Code = ApiEnum.查询失败, Message = ex.Message, data = null };
			}
		}

		/// <summary>
		/// 根据ID获取用户详情（包含角色和权限信息）
		/// </summary>
		/// <param name="userId">用户ID</param>
		/// <returns>用户详细信息，包含关联的角色和权限</returns>
		/// <remarks>
		/// 示例请求:
		/// GET /api/User/GetUserById?userId=1
		/// 
		/// 返回的用户信息包含：
		/// - 用户基本信息（用户名、邮箱、手机号等）
		/// - 关联的角色列表
		/// - 通过角色继承的所有权限列表
		/// </remarks>
		/// <response code="200">查询成功，返回用户详细信息</response>
		/// <response code="400">请求参数错误</response>
		/// <response code="404">用户不存在</response>
		/// <response code="500">服务器内部错误</response>
		[HttpGet]
		[ProducesResponseType(typeof(ApiResult<UserDto>), 200)]
		[ProducesResponseType(400)]
		[ProducesResponseType(404)]
		[ProducesResponseType(500)]
		public async Task<ApiResult<UserDto>> GetUserById([FromQuery] long userId)
		{
			try
			{
				var data = await _mediator.Send(new GetUserByIdQuery { UserId = userId });
				return new ApiResult<UserDto> { Code = ApiEnum.查询成功, Message = "查询成功", data = data };
			}
			catch (Exception ex)
			{
				return new ApiResult<UserDto> { Code = ApiEnum.查询失败, Message = ex.Message, data = null };
			}
		}

		/// <summary>
		/// 获取用户的所有权限列表（通过角色继承）
		/// </summary>
		/// <param name="userId">用户ID</param>
		/// <returns>用户拥有的所有权限列表</returns>
		/// <remarks>
		/// 示例请求:
		/// GET /api/User/GetUserPermissions?userId=1
		/// 
		/// 此接口会查询用户的所有角色，然后汇总所有角色拥有的权限（自动去重）。
		/// 如果用户没有角色或角色没有权限，返回空列表。
		/// </remarks>
		/// <response code="200">查询成功，返回权限列表</response>
		/// <response code="400">请求参数错误</response>
		/// <response code="404">用户不存在</response>
		/// <response code="500">服务器内部错误</response>
		[HttpGet]
		[ProducesResponseType(typeof(ApiResult<List<PermissionDto>>), 200)]
		[ProducesResponseType(400)]
		[ProducesResponseType(404)]
		[ProducesResponseType(500)]
		public async Task<ApiResult<List<PermissionDto>>> GetUserPermissions([FromQuery] long userId)
		{
			try
			{
				var data = await _mediator.Send(new GetUserPermissionsQuery { UserId = userId });
				return new ApiResult<List<PermissionDto>> { Code = ApiEnum.查询成功, Message = "查询成功", data = data };
			}
			catch (Exception ex)
			{
				return new ApiResult<List<PermissionDto>> { Code = ApiEnum.查询失败, Message = ex.Message, data = null };
			}
		}
	}
}

